using System;
using System.Web;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using log4net.Config;

namespace Project.Library.HttpApplications
{
    /// <summary>
    /// Implement the basic implementation for a Web project using Windsor
    /// </summary>
    public abstract class HttpWindsorApplication : HttpApplication, IContainerAccessor
    {
        #region Properties

        private static IWindsorContainer windsorContainer;

        /// <summary>
        /// Implements <see cref="IContainerAccessor" /> so that Castle facilities
        /// can gain access to the <see cref="HttpApplication" />.
        /// </summary>
        public IWindsorContainer Container
        {
            get { return windsorContainer; }
        }

        /// <summary>
        /// Provides a globally available access to the <see cref="IWindsorContainer" /> instance.
        /// </summary>
        public static IWindsorContainer WindsorContainer
        {
            get { return windsorContainer; }
        }

        #endregion

        /// <summary>
        /// Handles the Start event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public virtual void Application_Start(object sender, EventArgs e)
        {
            // Initialize log4net
            XmlConfigurator.Configure();

            // Create the Windsor Container for IoC.
            // Supplying "XmlInterpreter" as the parameter tells Windsor 
            // to look at web.config for any necessary configuration.
            windsorContainer = new WindsorContainer(new XmlInterpreter());
        }

        /// <summary>
        /// Handles the End event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public virtual void Application_End(object sender, EventArgs e)
        {
            windsorContainer.Dispose();
        }

        #region Abstract events

        public abstract void Application_Error(object sender, EventArgs e);

        public abstract void Session_Start(object sender, EventArgs e);

        /// <summary>
        /// 
        /// </summary>
        /// <remarks>
        /// The Session_End event is raised only when the sessionstate mode
        /// is set to InProc in the Web.config file. If session mode is set to StateServer 
        /// or SQLServer, the event is not raised.
        /// </remarks>
        public abstract void Session_End(object sender, EventArgs e);

        #endregion
    }
}